#include <stdio.h>
#include <fcntl.h>
#include <sys/types.h>
#include <semaphore.h>

#include <stdlib.h>
#include <unistd.h>
#include <time.h>

#include <sys/stat.h>
#include <string.h>

#define  SEM_NAME "mysem"
#define  SEM_NAME2 "mysem2"
#define  DATA_FILE "a.txt"

#define  KEY 157

int main(int argc, char const *argv[])
{
    //  打开信号量
    sem_t *sem = sem_open(SEM_NAME, O_RDWR);
    sem_t *sem2 = sem_open(SEM_NAME2, O_RDWR);

    sem_wait(sem2);
    int fd = open(DATA_FILE, O_RDWR);
    // 读取文件中每一行, 查找新数据所在行
    char ch;
    while(1){
        lseek(fd, 3, SEEK_CUR);
        read(fd, &ch, 1);
        if(ch == '\n') break;
        else{
            lseek(fd, 4, SEEK_CUR); 
        }
    }
    lseek(fd, -4, SEEK_CUR);
    char numbuf[10] = "";
    read(fd, numbuf, 3);
    printf("read data is %s\n", numbuf);

    int m = atoi(numbuf) ^ KEY;
    bzero(numbuf, 10);
    sprintf(numbuf,",%d\n", m);
    write(fd, numbuf, 5);
    printf("--->OK\n");
    close(fd);
    sem_post(sem); // 通知第一个程序可以再生产新的数据  

    sem_close(sem);  // 关闭信号量
    sem_close(sem2);  // 关闭信号量
    return 0;
}
